package com.fintech.pangu.autoconfigure.security.authentication.token;

import com.fintech.pangu.autoconfigure.security.properties.PanGuSecurityProperties;
import com.fintech.pangu.security.authentication.token.AuthenticationTokenServices;
import com.fintech.pangu.security.authentication.token.AuthenticationTokenStore;
import com.fintech.pangu.security.jwt.provider.authentication.token.JwtAuthenticationTokenServices;
import com.fintech.pangu.security.jwt.provider.authentication.token.JwtAuthenticationTokenStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

/**
 * JWT认证token的生成、存储 自动配置
 */
@Configuration
@EnableConfigurationProperties(PanGuSecurityProperties.class)
@ConditionalOnClass(JwtAuthenticationTokenServices.class)  // classpath包含pangu-componect-security-jwt包
//@ConditionalOnProperty(value = "pangu.security.authentication.token.type", havingValue = "jwt", matchIfMissing = false) // 只要是引入了jwt组件，就不用判断类型
@ConditionalOnBean(AuthenticationTokenMarkerConfiguration.Marker.class)  // Marker被使用者标记
public class JwtAuthenticationTokenAutoConfiguration {

    /**
     * PanGu安全相关所有配置
     */
    @Autowired
    private PanGuSecurityProperties panGuSecurityProperties;

    /**
     * JWT token store
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(AuthenticationTokenStore.class)
    public AuthenticationTokenStore jwtAuthenticationTokenStore(){
        return new JwtAuthenticationTokenStore();
    }


    /**
     * JWT认证令牌服务类
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(AuthenticationTokenServices.class)
    public AuthenticationTokenServices jwtAuthenticationTokenServices(){
        String secret = panGuSecurityProperties.getAuthentication().getToken().getJwt().getSecret();
        Assert.hasText(secret, "authentication token type[jwt] secret can not be empty ");

        JwtAuthenticationTokenServices jwtAuthenticationTokenServices = new JwtAuthenticationTokenServices();
        jwtAuthenticationTokenServices.setSecret(secret); // 密匙
        jwtAuthenticationTokenServices.setJwtExpireInSeconds(panGuSecurityProperties.getAuthentication().getToken().getJwt().getExpireInSeconds()); // jwt过期时间
        jwtAuthenticationTokenServices.setTokenStore(jwtAuthenticationTokenStore()); // jwt token store

        return jwtAuthenticationTokenServices;
    }


}
